package com.sfdk.graphics.core
{
import com.sfdk.graphics.enums.ColorConstant;
import com.sfdk.graphics.ui.parts.ComponentBase;

import flash.display.Graphics;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.system.System;
import flash.utils.Timer;

public class DebugWindow extends ComponentBase
	{
		private var _fpsTextField : TextFieldEx;
		private var _memoryTextField : TextFieldEx;
		private var _fpsTimer : Timer;
		private var _fpsCount : int;
		
		public function DebugWindow()
		{
			super();
		}
		
		/** Initialisation **/
		
		protected override function createView(e : Event) : void
		{
			var g : Graphics = this.graphics;
			
			g.clear();
			g.beginFill(ColorConstant.marronFonce, 1);
			g.drawRoundRect(0, 0, stage.stageWidth , 40, 5, 5);
			g.endFill();
			g.lineStyle(1, ColorConstant.blanc);
			g.beginFill(ColorConstant.blanc, 0);
			g.drawRoundRect(2, 2, stage.stageWidth - 5, 35, 5, 5);
			g.endFill();
			g.lineStyle();
			
			_fpsTextField = new TextFieldEx();
			_fpsTextField.text = "fps : calcul en cours";
			attachChild(_fpsTextField, 5, 10, "fpsCount");
			
			_memoryTextField = new TextFieldEx();
			_memoryTextField.text = "| Mémoire totale : "+int(System.totalMemory / 1000)+ "Ko ("+int(System.totalMemory / 1000000)+" Mo)";
			attachChild(_memoryTextField, 10 + _fpsTextField.textWidth, 10, "memoryCount");
		
			_fpsTimer = new Timer(2000, 0);
			_fpsTimer.addEventListener(TimerEvent.TIMER, onFpsTimerTick, false, 0, true);
			_fpsTimer.start(); 
			
			addEventListener(Event.ENTER_FRAME, onFpsEnterFrame, false, 0, true);
		}
		
		protected override function cleanView(e : Event) : void
		{
			this.removeAllChildren();
			
			_fpsTimer.stop();
			_fpsTimer = null;
			_fpsCount = 0;
			
			removeEventListener(Event.ENTER_FRAME, onFpsEnterFrame);
		}
		
		/** Ui Handlers **/
		
		private function onFpsTimerTick(e : TimerEvent) : void
		{
			_fpsTextField.text = "fps : "+_fpsCount / 2;
			_memoryTextField.x = 10 + _fpsTextField.textWidth;
			_memoryTextField.text = "| Mémoire totale : "+int(System.totalMemory / 1000)+ "Ko ("+int(System.totalMemory / 1000000)+" Mo)";
			_fpsCount = 0;
		}
		
		private function onFpsEnterFrame(e : Event) : void
		{
			_fpsCount++;
		}
	}
}